<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="70px">
      <el-form-item label="表单类型" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择" clearable>
          <el-option
            v-for="item in businessTypeOptions"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          style="width: 250px"
          v-model="dateRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row v-if="false" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="false" type="info" plain icon="RefreshLeft" disabled> 撤回</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Printer" disabled> 打印</el-button>
      </el-col>
      <el-col v-if="false" :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete({})">
          删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>
    <el-table
      :data="list"
      @selection-change="handleSelectionChange"
      max-height="620px"
      tooltip-effect
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column
        label="审核时间"
        prop="taskProcessTime"
        align="center"
        v-if="currentIndex === 1"
      />
      <el-table-column
        label="单据类型"
        prop="businessType"
        align="center"
        :formatter="businessTypeFormatter"
      />
      <el-table-column label="单据状态" prop="status" align="center">
        <template #default="{ row }">
          <span
            v-if="currentIndex === 0 || currentIndex === 1"
            class="status-box"
            :style="{ background: statusClassConfig[row?.instance?.status] }"
          >
            {{ row?.instance?.status }}
          </span>
          <span v-else class="status-box" :style="{ background: statusClassConfig[row.status] }">
            {{ row.status }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="单据编号" prop="businessCode" align="center" width="185">
        <template #default="{ row }">
          <div class="text-left">{{ row.businessCode }}</div>
        </template>
      </el-table-column>
      <el-table-column label="事由/备注" prop="reason" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="text-left truncate"
            >{{ row?.instance ? row?.instance?.reason : row.reason ? row.reason : '-' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="申请人" prop="initiatorName" align="center">
        <template #default="{ row }">
          <span>{{ row?.instance ? row?.instance?.initiatorName : row.initiatorName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" prop="" align="center">
        <template #default="{ row }">
          <span>{{ handleTime(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="制单人" prop="initiatorName" align="center">
        <template #default="{ row }">
          <span>{{ row?.instance ? row?.instance?.initiatorName : row.initiatorName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="" align="center" width="250">
        <template #default="{ row }">
          <el-button v-if="currentIndex !== 0" link type="primary" @click="handleDetail(row)"
            >详情
          </el-button>
          <el-button v-if="currentIndex === 0" link type="primary" @click="handleDetail(row)"
            >审批
          </el-button>
          <el-button
            v-if="currentIndex === 2 && row.status === '审批中'"
            link
            type="danger"
            @click="handleCancel(row)"
            >撤销流程
          </el-button>
          <el-button
            v-if="currentIndex === 2 && (row.status === '已撤销' || row.status === '审批退回')"
            link
            type="primary"
            @click="handleEdit(row)"
            >修改
          </el-button>
          <el-button link type="primary" @click="handleLog(row)">流程图</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      @pagination="getList"
    />
    <el-dialog v-model="visible" title="系统提示" width="500">
      <el-form :model="form" ref="formRef" :rules="rules">
        <el-form-item label="操作方式" prop="outcome">
          <el-select v-model="form.outcome">
            <el-option
              v-for="item in process_line_node_name"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核意见" prop="remark">
          <el-input
            class="mt-2"
            type="textarea"
            placeholder="请输入审核意见"
            v-model="form.remark"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <FlowView v-model="flowVisible" :flow-data="flowData" />
  </div>
</template>

<script setup>
  import { ref } from 'vue';
  import modal from '@/plugins/modal';
  import {
    businessTypeData,
    cancelFlow,
    formAuditing,
    getFlowXml,
  } from '@/api/flowable/process-center';
  import { useDict } from '@/utils/dict';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { handleFlowNodeData } from '@/utils/flow';
  import FlowView from '@/components/FlowView/detail.vue';

  const { process_line_node_name } = useDict('process_line_node_name');
  defineProps({
    list: {
      type: Array,
      default: () => [],
    },
    total: {
      type: Number,
      default: 0,
    },
    deptOptions: {
      type: Array,
      default: () => [],
    },
    currentIndex: {
      type: Number,
      default: 0,
    },
  });
  const emits = defineEmits(['getList', 'deleteFn', 'detailFn', 'getCountData', 'editFn']);

  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const queryParams = ref({});
  const queryRef = ref(null);
  const multiple = ref(true);
  const ids = ref([]);
  const visible = ref(false);
  const form = ref({});
  const rules = {
    outcome: [{ required: true, trigger: 'blur', message: '操作方式不能为空' }],
    remark: [{ required: true, trigger: 'blur', message: '审核意见不能为空' }],
  };
  const formRef = ref(null);
  const flowVisible = ref(false);
  const flowData = ref('');
  const dateRange = ref([]);
  const businessTypeOptions = ref([]);
  const statusClassConfig = {
    审批中: 'linear-gradient(180deg, #ef893f 0%, #ffbd5a 100%)',
    已完成: 'linear-gradient(180deg, #34D84E 0%, #B1FFC2 100%)',
    已撤销: 'linear-gradient(180deg, #3688FF 0%, #C5DAFD 100%)',
    审批退回: 'linear-gradient(rgb(255 54 54) 0%, rgb(253 197 197) 100%)',
  };

  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    multiple.value = !selection.length;
  }

  function handleDelete(row) {
    const _ids = row?.id ?? ids.value.join(',');
    emits('deleteFn', _ids);
  }

  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  function resetQuery() {
    queryRef.value?.resetFields();
    dateRange.value = [];
    handleQuery();
  }

  function getList() {
    if (dateRange.value.length) {
      queryParams.value.dateRangeTimeVo = {
        begin: dateRange.value[0],
        end: dateRange.value[1],
      };
    } else {
      delete queryParams.value.dateRangeTimeVo;
    }
    emits('getList', pageParams.value, queryParams.value);
  }

  function submitForm() {
    formRef.value.validate((valid) => {
      if (valid) {
        formAuditing(form.value).then(() => {
          modal.msgSuccess('操作成功');
          visible.value = false;
          getList();
          emits('getCountData');
        });
      }
    });
  }

  function handleDetail(row) {
    emits('detailFn', row);
  }

  async function handleLog(row) {
    let id = null;
    if (row.instance) {
      id = row.instance.processInstanceId;
    } else {
      id = row.processInstanceId;
    }
    const res = await getFlowXml(id);
    if (!res.data.bpmnContent) {
      modal.msgWarning('对应流程图不存在');
      return;
    }
    flowData.value = {
      xmlData: res.data.bpmnContent,
      nodeData: handleFlowNodeData(res.data),
    };
    flowVisible.value = true;
  }

  function handleCancel(row) {
    ElMessageBox.prompt('请输入撤销原因', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'textarea',
      inputValidator: (val) => {
        if (val === null || val?.length > 250) {
          return false;
        }
      },
      inputErrorMessage: '请输入撤销原因，最多可输入250个字符',
    })
      .then(({ value }) => {
        cancelFlow({
          businessId: row.businessId,
          businessType: row.businessType,
          deleteReason: value,
        }).then((res) => {
          ElMessage({
            type: 'success',
            message: res.msg,
          });
          getList();
          emits('getCountData');
        });
      })
      .catch(() => {});
  }

  function handleEdit(row) {
    emits('editFn', row);
  }

  async function getBusinessTypeData() {
    const res = await businessTypeData();
    businessTypeOptions.value = res.data;
  }

  function businessTypeFormatter(row) {
    return businessTypeOptions.value?.find((f) => f.value === row.businessType)?.name;
  }

  function handleTime(row) {
    if (row?.instance) {
      return row?.instance?.updateTime ? row?.instance?.updateTime : row?.instance?.createTime;
    } else {
      return row?.updateTime ? row.updateTime : row.createTime;
    }
  }

  getBusinessTypeData();
</script>

<style scoped lang="scss">
  .status-box {
    padding: 6px;
    border-radius: 10px;
    color: #fff;
  }
</style>
